package tech.edwardvan.springsecuritydemo.security.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import tech.edwardvan.springsecuritydemo.common.ServerResponse;
import tech.edwardvan.springsecuritydemo.security.util.JwtTokenUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt认证成功处理器
 *
 * @author EdwardVan
 */
@RequiredArgsConstructor
public class JwtAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String token = jwtTokenUtil.createToken(userDetails);
        response.setContentType("application/json;charset=UTF-8");
        IoUtil.writeUtf8(response.getOutputStream(), true, JSONUtil.toJsonStr(ServerResponse.success(token)));
    }
}
